package com.wy2cloud.sample.resourceserver.config;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.util.matcher.AnyRequestMatcher;
import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher;
import org.springframework.web.accept.ContentNegotiationStrategy;
import org.springframework.web.accept.HeaderContentNegotiationStrategy;

/**
 * to use remote oauth server to authentication token
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
	
	private static final Logger logger=LoggerFactory.getLogger(ResourceServerConfig.class);

	@Value("${security.oauth2.client.client-id}")
	private String resoucreId;
	

    @Override
    public void configure(HttpSecurity http) throws Exception {

		
		http.csrf().disable()
		.exceptionHandling().authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
		//.defaultAuthenticationEntryPointFor(authenticationEntryPoint(), AnyRequestMatcher.INSTANCE)
		.and().authorizeRequests().anyRequest().authenticated()
		.and().httpBasic();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        //System.out.println("==========================Configuring ResourceServerSecurityConfigurer ");
        //resources.resourceId("oauth2-resource");
    	resources.resourceId(resoucreId);
    	logger.info("Configuring ResourceServerSecurityConfigurer resoucreId:{}", resoucreId);
        //super.configure(resources);
    }

}
